package com.lswms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lswms.common.constant.Constant;
import com.lswms.common.page.PageInfo;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.ConvertUtils;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dao.YnSignRecordDao;
import com.lswms.dto.YnSignRecordDTO;
import com.lswms.dto.YnUserDTO;
import com.lswms.dto.vo.req.QuerySignInfoReq;
import com.lswms.dto.vo.req.SignListReq;
import com.lswms.dto.vo.req.SignRecordListReq;
import com.lswms.dto.vo.resp.BeatSignResp;
import com.lswms.dto.vo.resp.QuerySignDetailResp;
import com.lswms.dto.vo.resp.SignListResp;
import com.lswms.entity.YnSignRecordEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.service.YnSignRecordService;
import com.lswms.service.YnSignService;
import com.lswms.service.YnUserService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
 * 挑战记录表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-05-06
 */
@Service
@Slf4j
public class YnSignRecordServiceImpl extends CrudServiceImpl<YnSignRecordDao, YnSignRecordEntity, YnSignRecordDTO> implements YnSignRecordService {
	
	@Autowired
	private YnSignService ynSignService;
	
	@Autowired
	private YnUserService ynUserService;
	

    @Override
    public QueryWrapper<YnSignRecordEntity> getWrapper(Map<String, Object> params){
    	Long id = (Long)params.get("id");

        QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(id != null, "id", id);

        return wrapper;
    }

    /**
     * 查询是否参加本期挑战
     */
	@Override
	public List<YnSignRecordEntity> querySign(YnUserEntity ynuser) {
		String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
		//查询期数
		QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<YnSignRecordEntity>();
		wrapper.eq(StringUtils.isNotBlank(yyyyMMdd), "sign_no", yyyyMMdd);
		wrapper.eq("user_id", ynuser.getId());
		List<YnSignRecordEntity> sign = baseDao.selectList(wrapper);
		if(sign.size() <= 0){
			return null;
		}
		return sign;

	}

	/**
	 * 查询用户挑战记录
	 */
	@Override
	public List<YnSignRecordEntity> queryUserSign(String signNo, String type,Long userId,String yesnoRead) {
		log.info("查询用户挑战记录signNo:{},type:{},yuser:{}",signNo,type,userId);
		QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<YnSignRecordEntity>();
		wrapper.eq(StringUtils.isNotBlank(signNo), "sign_no", signNo);
		wrapper.eq(userId != null,"user_id", userId);
		wrapper.eq(StringUtils.isNotBlank(type),"type", type);
		wrapper.eq(StringUtils.isNotBlank(yesnoRead),"yesno_read", yesnoRead);
		List<YnSignRecordEntity> sign = baseDao.selectList(wrapper);
		return sign;
	}
	/**
	 * 挑战记录
	 */
	@Override
	public PageInfo<SignListResp> signList(SignListReq dto,YnUserEntity ynuser) {
		log.info("挑战记录，参数dto:{},ynuser:{}",JSON.toJSONString(dto),JSON.toJSONString(ynuser));
        QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", ynuser.getId());
        if("1".equals(dto.getType())){
        	wrapper.isNotNull("sign_time");
        }
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", dto.getPageNo());
        params.put("limit", dto.getPageSize());

		IPage<YnSignRecordEntity> pageInfo = baseDao.selectPage(getPage(params, "create_date", false),wrapper);
		
		List<SignListResp> list = new ArrayList<SignListResp>();
		for(YnSignRecordEntity entity : pageInfo.getRecords()){
			
			SignListResp resp = new SignListResp();
			resp.setId(entity.getId());
			resp.setSignNo(entity.getSignNo());
			resp.setType(entity.getType());
			resp.setAmount(MoneyUtil.bigDecimal2String(entity.getAmount(), 2));
			//查询期数详情
			QuerySignInfoReq infoDto = new QuerySignInfoReq();
			infoDto.setSignNo(entity.getSignNo());
			infoDto.setType(entity.getType());
			QuerySignDetailResp detailResp = ynSignService.querySignDetail(infoDto, ynuser);
			//(0立即挑战，1等待打卡，2立即打卡,3等待派奖，4挑战成功，5挑战失败)
			resp.setStatus(detailResp.getSignStatus());
			if("5".equals(detailResp.getSignStatus())){ 
				resp.setFailTip("Lakukan upaya gigih untuk menjadikan diri Anda kebiasaan yang baik!");
			}
			resp.setOpenTime(detailResp.getOpenTime());
			resp.setOpenTimeh(detailResp.getOpenTimeh());
			resp.setSignTime(detailResp.getSignTime());
			resp.setSignTimeh(detailResp.getSignTimeh());
			list.add(resp);
		}
		
		PageInfo<SignListResp> pageList = new PageInfo<SignListResp>();
		pageList.setCount(pageInfo.getTotal());
		pageList.setList(list);
		pageList.setPageNo(Long.parseLong(dto.getPageNo()));
		pageList.setPages(pageInfo.getPages());
		pageList.setPageSize(Long.parseLong(dto.getPageSize()));
		log.info("挑战记录，结果:{}",JSON.toJSONString(pageList));
		return pageList;
	}

	/**
	 * 查询本期最早打卡、最佳手气、历史最多参与
	 */
	@Override
	public BeatSignResp bestTime(String signNo, String type) {
		log.info("查询本期最早打卡signNo:{},type:{}",signNo,type);
		//查询最早打卡列表
		QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<YnSignRecordEntity>();
		wrapper.eq(StringUtils.isNotBlank(signNo), "sign_no", signNo);
		wrapper.eq(StringUtils.isNotBlank(type),"type", type);
		wrapper.isNotNull("sign_time");
		wrapper.orderByAsc("sign_time");
		List<YnSignRecordEntity> sign = baseDao.selectList(wrapper);
		//返回
		BeatSignResp resp = null;
		if(sign != null && sign.size() > 0){
			resp = new BeatSignResp();
			YnSignRecordEntity signEn = sign.get(0);
			YnUserDTO dto = ynUserService.get(signEn.getUserId());
			resp.setName(dto.getUsername());
			resp.setType("0");
			resp.setValue(ZqDateUtil.Hms(signEn.getSignTime())+"打卡");
		}else{
			resp = new BeatSignResp();
			resp.setName("Iysla");
			resp.setType("0");
			resp.setValue("05:00:00 Punch in");
		}
		return resp;
	}
	@Override
	public BeatSignResp bestMoney(String signNo, String type) {
		log.info("查询本期最早打卡signNo:{},type:{}",signNo,type);
		//查询最佳手气列表
		QueryWrapper<YnSignRecordEntity> wrapper = new QueryWrapper<YnSignRecordEntity>();
		wrapper.eq(StringUtils.isNotBlank(signNo), "sign_no", signNo);
		wrapper.eq(StringUtils.isNotBlank(type),"type", type);
		wrapper.isNotNull("sign_time");
		wrapper.orderByDesc("amount");
		List<YnSignRecordEntity> sign = baseDao.selectList(wrapper);
		//返回
		BeatSignResp resp = null;
		if(sign != null && sign.size() > 0){
			resp = new BeatSignResp();
			YnSignRecordEntity signEn = sign.get(0);
			YnUserDTO dto = ynUserService.get(signEn.getUserId());
			resp.setName(dto.getUsername());
			resp.setType("1");
			resp.setValue(MoneyUtil.bigDecimal2String(signEn.getAmount(), 2));
		}else{
			resp = new BeatSignResp();
			resp.setName("olsie");
			resp.setType("1");
			resp.setValue("10000");
		}
		return resp;
	}
	@Override
	public BeatSignResp bestNum(String signNo, String type) {
		//查询历史最多参与
		Map<String,Object> map = new HashMap<>();
		Map<String,Object> resp = baseDao.queryBestNum(map);
		//返回
		BeatSignResp resp1 = null;
		if(resp != null){
			String num = resp.get("totalNum").toString();
			String userId = resp.get("userId").toString();
			YnUserDTO dto = ynUserService.get(Long.parseLong(userId));
			if(dto != null){
				resp1 = new BeatSignResp();
				resp1.setName(dto.getUsername());
				resp1.setType("2");
				resp1.setValue("Partisipasi kumulatif"+num+"");
			}
		}else{
			resp1 = new BeatSignResp();
			resp1.setName("0268");
			resp1.setType("2");
			resp1.setValue("Partisipasi kumulatif1992");
		}
		return resp1;
	}

	@Override
	public PageInfo<YnSignRecordDTO> listByCondition(SignRecordListReq dto) {
		Map<String,Object> pageParam = new HashMap<>();
		pageParam.put(Constant.PAGE,dto.getPageNo());
		pageParam.put(Constant.LIMIT, dto.getPageSize());
		IPage pageList =  baseDao.selectPage(
				getPage(pageParam,"create_date",false),
				new QueryWrapper<YnSignRecordEntity>()
						.le(StrUtil.isNotEmpty(dto.getEndTime()), "create_date", dto.getEndTime())
						.ge(StrUtil.isNotEmpty(dto.getStartTime()), "create_date", dto.getStartTime())
						.eq(StrUtil.isNotEmpty(dto.getSignNo()), "sign_no", dto.getSignNo())
						.eq(StrUtil.isNotEmpty(dto.getType()), "type", dto.getType())
						.eq(StrUtil.isNotEmpty(dto.getStatus()), "status", dto.getStatus())
		);


		PageInfo<YnSignRecordDTO> pageInfo = new PageInfo<YnSignRecordDTO>();
		pageInfo.setCount(pageList.getTotal());
		pageInfo.setList(pageList.getRecords());
		pageInfo.setPages(pageList.getPages());
		pageInfo.setPageNo(Long.parseLong(dto.getPageNo()));
		pageInfo.setPageSize(Long.parseLong(dto.getPageSize()));
		return pageInfo;
	}
}